package com.zlt.service.impl;

import com.zlt.dao.ChatMessageDao;
import com.zlt.dao.Impl.ChatMessageDaoImpl;
import com.zlt.dao.Impl.UserDaoImpl;
import com.zlt.dao.UserDao;
import com.zlt.entity.ChatMessageDetail;
import com.zlt.entity.ChatMessageMain;
import com.zlt.service.ChatMessageService;
import com.zlt.util.JWTUtil;
import com.zlt.util.JedisUtil;
import com.zlt.vo.ChatMessageVo;
import com.zlt.vo.ChatVo;
import redis.clients.jedis.Jedis;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ChatMessageServiceImpl implements ChatMessageService {

    private ChatMessageDao chatMessageDao = new ChatMessageDaoImpl();

    private UserDao userDao = new UserDaoImpl();

    @Override
    public int addMain(ChatMessageMain chatMessageMain) {
        return chatMessageDao.insertMainByClass(chatMessageMain);
    }

    @Override
    public List<ChatVo> showUserChatList(String token) {
        String username = JWTUtil.getUsername(token);
        Integer role = userDao.getUserRole(username);
        if ( role == 1 ) {//求职者身份查询招聘者
            return chatMessageDao.showSeekerChatList(username);
        } else {//招聘者身份查询求职者
            return chatMessageDao.showRecruiterChatList(username);
        }
    }

    @Override
    public int addDetail(int mainId, String thisUUID, String userUid, Character type, Object content, Date date, Character hasRead) {
        return chatMessageDao.insertDetailByParams(mainId, thisUUID, userUid, type, content, date, hasRead);
    }

    @Override
    public int addDetail(ChatMessageDetail chartMessageDetail) throws SQLException {
        return addDetail(chartMessageDetail.getMainId(), chartMessageDetail.getSendUser(), chartMessageDetail.getReceiveUser(), chartMessageDetail.getContent(), chartMessageDetail.getHasRead());
    }

    @Override
    public Integer addMain(String src, String dest) {
        /*
        1. 存在该记录，就不做处理
        2. 不存在该记录，就添加该记录
         */
        ChatMessageMain exist = chatMessageDao.isExist(src, dest);
        if (exist != null) {//存在该记录
            return exist.getId();
        } else {//不存在该记录，添加记录
            return chatMessageDao.insertRecord(src, dest);
        }
    }

    @Override
    public Integer addDetail(Integer mainId, String uid, String to, String content, char hasRead) throws SQLException {
        return chatMessageDao.insertDetailByParams(mainId, uid, to, content, hasRead);
    }

    @Override
    public List<ChatMessageMain> chatList(String uid) {
//        将聊天对象存入Redis中
        Jedis jedis = JedisUtil.getConnection();
        List<ChatMessageMain> list = new ArrayList<>();
        Set<String> smembers = jedis.smembers(uid);
        boolean empty = smembers.isEmpty();
        if (!smembers.isEmpty()) {//Redis中有数据
            Iterator<String> iterator = smembers.iterator();
            while (iterator.hasNext()) {
                ChatMessageMain chat = new ChatMessageMain();
                chat.setRecruiters(iterator.next());
                list.add(chat);
            }
            return list;
        } else {//Redis中不存在，找数据库
            try {
                list = chatMessageDao.selectChatList(uid);
                if (list.isEmpty()) {//没有聊天记录
                    return null;
                }
                //查询到数据,放Redis
                list.forEach(e ->
                        jedis.sadd(uid, e.getRecruiters())
                );
                return list;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


    }

    @Override
    public List<ChatMessageDetail> chatDetailList(String src, String dest) {
        try {
            return chatMessageDao.selectChatDetail(src, dest);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Integer addMainTable(String user1, String user2, String cid, String jid) {
        ChatMessageMain exist = chatMessageDao.isExist(user1, user2);
        if (exist != null) {//存在该记录
            return exist.getId();
        } else {//不存在该记录，添加记录
            return chatMessageDao.addMain(user1, user2, cid, jid);
        }
    }

    @Override
    public List<ChatMessageVo> showChatsByPhone(String token, String phone) {
        String phone1 = JWTUtil.getUsername(token);
        Integer role = userDao.getUserRole(phone1);

        List<ChatMessageVo> chatMessageVos = new ArrayList<>();

        // phone是目标的username；phone1是当前的username
        List<ChatMessageDetail> list = null;
        if (role == 1) {//求职者
            list = chatMessageDao.showChats(phone1, phone);
        } else {//招聘者
            list = chatMessageDao.showChats(phone, phone1);
        }

        for (ChatMessageDetail chatMessageDetail : list) {
            chatMessageVos.add(new ChatMessageVo(
                    chatMessageDetail.getId(),
                    chatMessageDetail.getMainId(),
                    chatMessageDetail.getSendUser(),
                    chatMessageDetail.getReceiveUser(),
                    chatMessageDetail.getContentType(),
                    chatMessageDetail.getContent(),
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(chatMessageDetail.getCreateTime().getTime()),
                    chatMessageDetail.getHasRead()
            ));
        }
        return chatMessageVos;
    }

    @Override
    public Integer getMainId(String uid1, String uid2) {
        return chatMessageDao.getMain(uid1, uid2);
    }

}
